package com.tqjc.execute.step;

import com.tqjc.execute.cache.TaskStatus;
import com.tqjc.execute.cache.entity.WorkStatus;
import com.tqjc.execute.cache.service.TaskStatusCacheService;
import com.tqjc.execute.consts.WorkConst;
import com.tqjc.execute.exception.TaskRunningException;
import com.tqjc.execute.task.entity.Task;
import com.tqjc.execute.task.entity.TaskApart;
import com.tqjc.execute.task.service.TaskApartService;
import com.tqjc.execute.task.service.impl.TaskApartServiceImpl;
import com.tqjc.execute.utils.PlcOperator;
import com.tqjc.execute.work.callback.TaskCallback;
import com.tqjc.system.core.util.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Description: 移动天车步骤
 * @author: pzy
 * @date: 2023年05月18日 16:33
 */

@Slf4j
@Component
@Scope("prototype")
public class MoveCraneStep extends TaskApart implements TaskCallback {
    @Resource
    PlcOperator plcOperator;

    @Resource
    TaskStatus taskStatus;

    public MoveCraneStep() {
        this.setType("move");
    }

    @Override
    public void onPreExecute() {
        try {
            log.info("开始执行步骤前置，{}", getType());

            WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setNowStep(getType());
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);

            setBeginTime(new Date());
            log.info("步骤前置执行结束，{}", getType());
        } catch (Exception e) {
            log.error(getType()+"前置出现异常",e);
            e.printStackTrace();
        }
    }

    @Override
    public void onPostExecute() {
        try {
            log.info("开始执行步骤后置，{}", getType());
            setEndTime(new Date());
            SpringUtils.getBean(TaskApartServiceImpl.class).insert(this);

            //修改步骤状态
            WorkStatus status = taskStatus.getWorkStatusByCraneType(getCraneType());
            status.setNowStep("");
            taskStatus.setWorkStatusByCraneType(getCraneType(), status);
            log.info("步骤后置执行结束，{}", getType());

            //清除bean
            destroy();
        } catch (Exception e) {
            log.error(getType()+"后置出现异常",e);
            e.printStackTrace();
        }
    }

    /**
     * create by: pzy
     * description: 根据任务生成步骤
     * create time: 2023/5/26 11:19
     *
     * @return void
     * @param: []
     */
    @Override
    public void setTaskApartByTask(Task task) {
        this.setCallback(this);
        this.setTaskId(task.getId());
        this.setSteelNo(task.getSteelNo());

    }

    @Override
    public void customAction() throws TaskRunningException {
        try {
            String craneType = this.getTask().getCraneType();
            //写入任务坐标
            log.info("步骤{}写入PLC开始", getType());

            //写入任务类型
//            TODO:等待确认任务类型
            plcOperator.writeValueByLabelAndCraneType(WorkConst.STEP_TYPE, "1", craneType);

            //写入任务开始
            plcOperator.writeValueByLabelAndCraneType(WorkConst.STEP_START, "1", craneType);
            log.info("步骤{}写入PLC完成,等待任务完成", getType());
            boolean isFinished = false;
            while (!isFinished) {
                if (Boolean.parseBoolean(plcOperator.readValueByLabelAndCraneType(WorkConst.STEP_FINISH, craneType))) {
                    isFinished = true;
                    log.info("PLC反馈步骤{}完成", getType());
                }
                //TODO:测试使用
                Thread.sleep(5000);
                isFinished = true;
                Thread.sleep(500);
            }

        } catch (Exception e) {
            throw new TaskRunningException(e.getMessage(), getTask().getCraneType());
        }


    }

    /**
     * @param :
     * @return void
     * @author Patienyon
     * @description 销毁Bean
     * @date 2023-06-28 10:41
     */
    @Override
    public void destroy() throws Exception {

    }

    /**
     * @param :
     * @return void
     * @author Patienyon
     * @description 初始化Bean
     * @date 2023-06-28 10:41
     */
    @Override
    public void afterPropertiesSet() throws Exception {

    }


}
